package wx_service

import (
	"crypto/sha1"
	"fmt"
	"net/http"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/utils/tools"
)

// WxPaService 微信公众号相关服务
type WxPaService struct {
}

func (wx *WxPaService) GetToken() (string, error) {
	appid := variable.Config.WxPa.Appid
	secret := variable.Config.WxPa.Secret

	// 调用api 生成token
	tokenUrl := variable.Config.Wx.TokenUrl
	getUrl := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", tokenUrl, appid, secret)
	resp, err := http.Get(getUrl)
	if err != nil {
		return "", fmt.Errorf("token生成失败")
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", fmt.Errorf("token解析失败")
	}
	accessToken := res["access_token"].(string)
	// expiresIn := res["expires_in"].(float64)
	// if len(accessToken) > 0 && expiresIn > 7000 && expiresIn < 7300 {
	// 	sc2 := variable.DB.Redis.Set(appid, accessToken, 7000*time.Second)
	// 	fmt.Println(sc2.Err())
	// }
	return accessToken, nil
}

func (wx *WxPaService) GetTicket() (string, error) {
	// 获取token信息
	token, err := wx.GetToken()
	if err != nil {
		log.Logger.Error("wx GetToken error:", err.Error())
		return "", err
	}
	ticketUrl := variable.Config.Wx.TicketUrl
	getUrl := fmt.Sprintf("%s?access_token=%s&type=jsapi", ticketUrl, token)
	resp, err := http.Get(getUrl)
	if err != nil {
		return "", fmt.Errorf("ticket 获取 失败")
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", fmt.Errorf("ticket解析失败")
	}
	ticket := res["ticket"].(string)
	return ticket, nil
}

// 获取jsapi 的签名

type JsApiSignatureReq struct {
	Timestamp string `json:"timestamp" form:"timestamp" validate:"required"`
	Noncestr  string `json:"noncestr" form:"noncestr" validate:"required"`
	Url       string `json:"url" form:"url" validate:"required"`
}

func (wx *WxPaService) GetJsApiSignature(req JsApiSignatureReq) (string, error) {
	// 获取ticket
	ticket, err := wx.GetTicket()
	if err != nil {
		log.Logger.Error("wx ticket error:", err.Error())
		return "", err
	}
	signStr := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", ticket, req.Noncestr, req.Timestamp, req.Url)
	log.Logger.Info("signStr:", signStr)

	s := sha1.New()
	s.Write([]byte(signStr))
	signature := fmt.Sprintf("%x", s.Sum(nil))
	return signature, nil
}
